'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { toast } from 'sonner'
import { createContract, CreateContractData } from '../actions/contract-actions'
import { ProjectSelector } from './project-selector'
import { VendorSelector } from './vendor-selector'

interface Project {
  id: number
  code: string
  name: string
  type: string
}

interface Vendor {
  id: number
  vendorName: string
  vendorCode: string | null
  status: string
}

interface ContractFormProps {
  onContractCreated?: (contract: { id: number; contractNo: string; contractName: string; status: string }) => void
}

export function ContractForm({ onContractCreated }: ContractFormProps) {
  const [loading, setLoading] = useState(false)
  const [selectedProject, setSelectedProject] = useState<Project | undefined>()
  const [selectedVendor, setSelectedVendor] = useState<Vendor | undefined>()
  const [formData, setFormData] = useState({
    contractName: '',
    status: 'TEST'
  })

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!selectedProject || !selectedVendor || !formData.contractName.trim()) {
      toast.error('모든 필수 항목을 입력해주세요.')
      return
    }

    setLoading(true)
    try {
      const contractData: CreateContractData = {
        projectId: selectedProject.id,
        vendorId: selectedVendor.id,
        contractName: formData.contractName,
        status: formData.status
      }
      
      const result = await createContract(contractData)
      
      if (result.success) {
        toast.success(result.message)
        // 폼 초기화
        setSelectedProject(undefined)
        setSelectedVendor(undefined)
        setFormData({
          contractName: '',
          status: 'TEST'
        })
        // 부모 컴포넌트에 생성된 계약 정보 전달
        onContractCreated?.(result.data)
      } else {
        toast.error(result.error)
      }
    } catch (error) {
      toast.error('계약 생성 중 오류가 발생했습니다.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>계약 생성</CardTitle>
        <CardDescription>
          새로운 테스트 계약을 생성합니다.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <Label>프로젝트 *</Label>
            <ProjectSelector
              selectedProject={selectedProject}
              onProjectSelect={setSelectedProject}
              disabled={loading}
            />
          </div>

          <div>
            <Label>벤더 *</Label>
            <VendorSelector
              selectedVendor={selectedVendor}
              onVendorSelect={setSelectedVendor}
              disabled={loading}
            />
          </div>

          <div>
            <Label htmlFor="contractName">계약명 *</Label>
            <Input
              id="contractName"
              type="text"
              value={formData.contractName}
              onChange={(e) => setFormData(prev => ({ ...prev, contractName: e.target.value }))}
              placeholder="계약명을 입력하세요"
            />
          </div>

          <div>
            <Label htmlFor="status">계약 상태</Label>
            <Select
              value={formData.status}
              onValueChange={(value) => setFormData(prev => ({ ...prev, status: value }))}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="TEST">TEST</SelectItem>
                <SelectItem value="DRAFT">DRAFT</SelectItem>
                <SelectItem value="ACTIVE">ACTIVE</SelectItem>
                <SelectItem value="PENDING">PENDING</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <Button type="submit" disabled={loading} className="w-full">
            {loading ? '생성 중...' : '계약 생성'}
          </Button>
        </form>
      </CardContent>
    </Card>
  )
}
